#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    open=false;
    startSend=false;
    sendTimes=0;
    
    SendInterval=50;
    ImageScale=0.5;
    isshowLine=false;

    ph=0;
    pw=0;

    ui->pushButton_2->setVisible(false);
    ui->btn3->setVisible(false);


    tcpServer = NULL;
    tcpSocket = NULL;
    
    tcpServer = new QTcpServer(this);
    tcpServer->listen(QHostAddress::Any,8543);

    connect(tcpServer,&QTcpServer::newConnection,[=](){
        //取出建立好连接的的套接字
        tcpSocket = tcpServer->nextPendingConnection();

        //获取对方的IP和端口
        QString ip = tcpSocket->peerAddress().toString();
        qint16  port = tcpSocket->peerPort();
        QString temp = QString("Client: [%1:%2]").arg(ip).arg(port);
        ui->info->setText(temp);
        isConnect=true;

        connect(tcpSocket, &QTcpSocket::readyRead,[=](){
             QByteArray buf = tcpSocket->readAll();
             cout <<"recv:"<<buf.data()<<endl;
             recvMess(buf.data());
         });
       
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::paintEvent(QPaintEvent *) {

//    if(pic.width()!=0)
//    {
//        QRectF target(0, 0, this->width(), this->height());
//        QRectF src(0, 0, pic.width(), pic.height());
//        QPainter painter1(this);
//        painter1.drawImage(target, pic, src);
//    }

}

void MainWindow::keyPressEvent(QKeyEvent *ev)
{
    if(ev->key()==Qt::Key_1&&!ev->isAutoRepeat())
    {
        SendInterval++;
        ui->info->setText(tr("Send Interval: ")+QString::number(SendInterval)+tr("ms"));
        timer->setInterval(SendInterval);
    }
    else if(ev->key()==Qt::Key_2&&!ev->isAutoRepeat())
    {
        SendInterval--;
        if(SendInterval<10)
            SendInterval=10;
        ui->info->setText(tr("Send Interval: ")+QString::number(SendInterval)+tr("ms"));
        timer->setInterval(SendInterval);
    }
}

void MainWindow::on_pushButton_clicked()
{
    if(ph==0){
        ImageScale=ui->input->text().toDouble();
        if(ImageScale>2.0||ImageScale<=0.05)
        {
            ui->input->setText(tr("scale is wrong!"));
            return ;
        }

        px=this->x();
        py=this->y();
        int iTitleBarHeight = style()->pixelMetric(QStyle::PM_TitleBarHeight);
        ph=this->height()+iTitleBarHeight;
        pw=this->width();

        ui->pushButton_2->setVisible(true);
        ui->btn3->setVisible(true);
        ui->input->setVisible(false);

        int x=ui->pushButton_2->x()+ui->pushButton_2->width()+50;
        int y=ui->pushButton_2->y();
        int w=ui->pushButton_2->width();
        int h=ui->pushButton_2->height();
        ui->pushButton->setGeometry(x,y,w,h);
        ui->pushButton->setText("Position");

        ui->btn3->setGeometry(x+w+50,y,w,h);

        show1.init(px,py,pw,ph);
    }
    else
    {
        px=this->x();
        py=this->y();
    }

    ui->info->setText(tr("W,H: ")+QString::number(pw)+tr(",")+QString::number(ph)+tr("  Qu:")+QString::number(ImageScale));
}

void MainWindow::on_pushButton_2_clicked()
{
    if(!open)
    {
        ui->pushButton_2->setText(tr("close"));
        timer = new QTimer(this);
        //设置定时器是否为单次触发。默认为 false 多次触发
        timer->setSingleShot(false);
        //启动或重启定时器, 并设置定时器时间：毫秒
        timer->start(SendInterval);
        //定时器触发信号槽
        connect(timer, SIGNAL(timeout()), this, SLOT(getScreen()));
        open=true;
    }
    else
    {
        ui->pushButton_2->setText(tr("start"));
        timer->stop();
        open=false;
    }
}



void MainWindow::recvMess(char data[])
{
    if(cmp_str(data,"size"))
    {
        QPixmap fullScreen;
        show1.close();
        fullScreen = QPixmap::grabWindow(QApplication::desktop()->winId(),px,py,pw,ph);
        if(isshowLine)
            show1.show();
        QImage src1=fullScreen.toImage();
        int h=src1.height()*ImageScale;
        int w=src1.width()*ImageScale;
        QImage src=src1.scaled(w,h);
        pic=QImage(src);

        char str[100];
        sprintf(str,"size:%d,%d,%lf",pic.width(),pic.height(),ImageScale);

        QByteArray t(str);
        sendMess(t);
    }
    else if(cmp_str(data,"first"))
    {
        sendImage(pic);
        this->update();
    }
    else if(cmp_str(data,"start"))
    {
        startSend=true;
    }
    else if(cmp_str(data,"stop"))
    {
        startSend=false;
    }
}


void MainWindow::sendMess(QByteArray data)
{
//    cout <<"send:"<<data.size()<<endl;
    if(!isConnect)
        return ;
    QByteArray m=data.append("#*#",3);
    int len=tcpSocket->write(m);
    if(len<0)
    {
        ui->info->setText(tr("client exit"));
        isConnect=false;
    }
}

void MainWindow::sendImage(QImage img)
{
    char temp[100];
    sprintf(temp,"img %d",img.byteCount());
    QByteArray t(temp,strlen(temp));
    sendMess(t);

    uchar *data=img.bits();
    QByteArray buf((char*)data,img.byteCount());
    sendMess(buf);

    sprintf(temp,"endImg");
    QByteArray t1(temp,strlen(temp));
    sendMess(t1);
}

void MainWindow::sendBytes(QByteArray buf)
{
    char temp[100];
    sprintf(temp,"img %d",buf.size());
//    cout <<"sendBytes:"<<buf.size()<<endl;
    QByteArray t(temp,strlen(temp));
    sendMess(t);

    sendMess(buf);

    sprintf(temp,"endData");
    QByteArray t1(temp,strlen(temp));
    sendMess(t1);
}


void MainWindow::getScreen()
{
    if(startSend)
    {
        sendTimes++;
        QPixmap fullScreen;
        show1.close();
        fullScreen = QPixmap::grabWindow(QApplication::desktop()->winId(),px,py,pw,ph);
        if(isshowLine)
            show1.show();

        QImage src1=fullScreen.toImage();
        int h=src1.height()*ImageScale;
        int w=src1.width()*ImageScale;
        QImage src=src1.scaled(w,h);

        if(sendTimes*SendInterval>MAXInterval)
        {
            pic=QImage(src);
            sendImage(src);
            this->update();
            sendTimes=0;
        }
        else
            calPic(src);
    }
}

void MainWindow::calPic(QImage src)
{
    if(pic.width()<1)
    {
        pic=QImage(src);
        this->update();
        return;
    }

//    QTime time;
//    time.start();

    QImage temp(src.width(),src.height(),src.format());
    int i=0;
    int size=temp.byteCount();
    uchar *data=temp.bits();
    uchar *last=pic.bits();
    uchar *now=src.bits();
    for(i=0;i<size;i++)
    {
        data[i]=now[i]-last[i];
        last[i]=now[i];
    }

    QByteArray compData=qCompress(data,size);
    sendBytes(compData);
    this->update();
}

void MainWindow::on_btn3_clicked()
{
    if(!isshowLine)
    {
        show1.setPlace(px,py);
        show1.show();
        isshowLine=true;
    }
    else
    {
        show1.close();
        isshowLine=false;
    }
}
